const http = require('http');
const qs = require('querystring');
const $context  = require('./context.js');
const Promise = require('bluebird');
//var request = require('request');
const request = require('superagent');

module.exports = {
  /**
   * 将客户端cookie对象转化成post请求中的cookie字符串格式为:a=b;c=d
   * @param cookie
   */
  dealCookie:function(cookies){
    if(!!cookies){
      let cookVals = "";
      //为所有的对象添加clone方法，即给内置原型(object,Array,function)增加原型属性,该方法很强大，也很危险
      if(typeof Object.prototype.clone ==="undefined"){
        Object.prototype.clone = function(){};
      }
      for(let i in cookies){
        if (cookies.hasOwnProperty(i)) { //filter,只输出man的私有属性
          cookVals += (i+'='+cookies[i]+';');
        };
      }
      cookVals = cookVals.substring(0,cookVals.length-1);
      return cookVals;
    }
  },
  /**
   * http post请求
   * @param interPath：接口路径（不带主机名和端口号）
   * @param params 参数（请求携带参数）
   * @param cookies 客户端cookie
   * @returns {bluebird|exports|module.exports}
   */
  doPost:function(interPath,params,cookies){
    let content = qs.stringify(params),//参数转换
      cookie_val = this.dealCookie(cookies),//cookie转换
      data = "";
    return new Promise(function(resolve, reject){
      console.log("$context.remoteUrl"+$context.remoteUrl + interPath);
      request
        .post($context.remoteUrl + interPath)
        .set('Content-Type', 'application/json')
        .set('Cookie',cookie_val)
        .send(content)
        .end(function(err,resp) {
          if(err){
            return reject(err);
          }
          if(resp.ok){
            var result = JSON.stringify(resp.text);
            return resolve(result);
          }
        }
      );
    });
  }
}


/* 第二种requestq请求方式
var content = qs.stringify(params);//参数转换
var cookie_val = this.dealCookie(cookies);//cookie转换
var data = "";
return new Promise(function(resolve, reject){
  var options = {
    hostname:$context.remoteHost,
    port: $context.remotePort,
    path: interPath,
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
      'Cookie': cookie_val
    }
  };
  var req = http.request(options, function (res) {
    res.setEncoding('utf8');
    res.on('data', function (chunk) {
      console.log('BODY: ' + chunk);
      data = JSON.stringify(chunk);
    });
    res.on('end', function() {
      return resolve(data);
    })
  });
  req.on('error', function (e) {
    console.log('problem with request: ' + e.message);
    return reject(e);
  });
  req.write(content);
  req.end();
});*/
